package com.hg.transaction.service;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hg.transaction.dao.UserDao;
import com.hg.transaction.entity.User;
import com.hg.transaction.entity.UserPointMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * created by skh on 2019/12/15
 */
@Service
@Slf4j
public class UserService extends ServiceImpl<UserDao, User> {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Transactional
    public void addUser(Integer userId, String userName) {
        User user = new User();
        user.setId(userId);
        user.setUserName(userName);
        userDao.insert(user);
        log.info("新增用户成功");
    }

    public void addUserAndPoint(String userName,Integer amount) {
        UserPointMessage userPointMessage = new UserPointMessage();
        userPointMessage.setUserId(1);
        userPointMessage.setUserName(userName);
        userPointMessage.setAmount(amount);

        org.springframework.messaging.Message<UserPointMessage> build = MessageBuilder.withPayload(userPointMessage).build();
        TransactionSendResult result = rocketMQTemplate.sendMessageInTransaction(null, "user", build, userPointMessage.getUserId());
        log.info("消息发送结果:{}",result);
    }
}
